#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./client_tcp server_ip server_port" << std::endl;
        return 1;
    }
    std::string serve_ip = argv[1];
    int serve_port = std::stoi(argv[2]);
    // 1创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket error" << std::endl;
        return 2;
    }
    // 2初始化
    struct sockaddr_in serve_addr;
    bzero(&serve_addr, sizeof(serve_addr));
    serve_addr.sin_family = AF_INET;
    serve_addr.sin_port = htons(serve_port);
    serve_addr.sin_addr.s_addr = inet_addr(serve_ip.c_str());
    // 3:conncet
    int n = connect(sockfd, (struct sockaddr *)&serve_addr, sizeof(serve_addr));
    if (n < 0)
    {
        std::cout << "connect fail" << std::endl;
        return 3;
    }
    // 4 echo client
    std::string message;
    while (1)
    {
        char buffer[1024];
        std::cout << "please input message#";
        std::getline(std::cin, message);

        n = write(sockfd, message.c_str(), message.size());
        if (n > 0)
        {
            int m = read(sockfd, buffer, sizeof(buffer));
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}